package com.guandeng.mall.portal.controller;

import com.guandeng.mall.common.api.CommonResult;
import com.guandeng.mall.portal.service.MemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.HashMap;
import java.util.Map;

@Controller
@Api(tags = "UmsMemberController", description = "会员登录注册管理")
public class UmsMember {
    private MemberService memberService;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @RequestMapping(value = "register", method = RequestMethod.POST)
    public CommonResult register(
            @RequestParam String username,
            @RequestParam String password,
            @RequestParam String telphone,
            @RequestParam String authCode
    ) {
        memberService.register(username, password, telphone, authCode);
        System.out.println(username);
        return CommonResult.success(null, "注册成功");
    }

    @RequestMapping(value = "login", method = RequestMethod.POST)
    public CommonResult login(@RequestParam String username, @RequestParam String password) {
        String token = memberService.login(username, password);
        if (token == null) {
            return CommonResult.validateFailed("账号密码错误");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        return CommonResult.success(tokenMap);
    }

    @ApiOperation("获取验证码")
    @RequestMapping(value = "/getAuthCode", method = RequestMethod.GET)
    public CommonResult getAuthCode(@RequestParam String telphone) {
        String authCode = memberService.generateAuthCode(telphone);
        return CommonResult.success(authCode, "获取验证码成功");
    }
}
